import axios from 'axios';
import { api_base_url, errorMap } from './constant.js';


export default function request({
    url,
    method,
    params,
}) {
    return axios.request({
        url,
        baseURL: api_base_url,
        params,
        method: method.toLocaleLowerCase(),
        // withCredentials: true,
        timeout: 3000,
    }).then(res => {
        if (res.status === 200 && res.data && res.data.code === 1) {
            return Promise.resolve(res.data);
        }

        return Promise.reject({
            code: res.data.code,
            _message: res.data.message,
            data: res.data.data
        });
    }).catch(error => {
        let errInfo = {};
    
        if (error._message) {
            errInfo = error;
        } else {
            const errStr = error.toString();
            console.log(error, errStr);
            if (errStr.indexOf('500') !== -1) {
                errInfo = errorMap['500'];
            } else if (errStr.indexOf('timeout') !== -1) {
                errInfo = errorMap['timeout'];
            } else {
                errInfo = errorMap['default'];
            }
        }

        return Promise.reject(errInfo);
    })
}